<?php
class child_c2_task_model {
    
    
    /**
     * 注入片源（以分集为单位,切片完成后调用）
     * $index_media array(
     * 'nns_video_id'
     * 'nns_video_index_id'
     * 'nns_task_id'
     * 'nns_new_dir'
     * 'nns_media_ids'
     * )
     */
    static public function add_movies_by_vod_index($index_media,$sp_id){
        include dirname(dirname(dirname(dirname(__FILE__)))).'/'.$sp_id.'/define.php';
        DEBUG && i_write_log_core('--注入片源--');
        $db = nn_get_db(NL_DB_WRITE);
        $sql = "select nns_pinyin from nns_vod where nns_id='".$index_media['nns_video_id']."'";
        $pinyin = nl_db_get_col($sql,$db);
        $action = 'REGIST';
        $sql = "select * from nns_vod_media where nns_deleted != 1 and nns_vod_id='{$index_media['nns_video_id']}' and nns_vod_index_id='{$index_media['nns_video_index_id']}' and nns_id='{$index_media['nns_media_id']}' order by nns_kbps desc limit 1";
        $medias = nl_db_get_all($sql,$db);
        if(is_array($medias) && count($medias)>0){
            $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
            $xml_str .= '<Objects>';
            $xml_str .= '<Object ElementType="Movie" ID="' .$index_media['nns_media_id']. '" Action="DELETE" Code="' .$index_media['nns_media_id']. '">';   
            $xml_str .= '</Object>';
            $media = array();
            $media_arr = array();
            $media_url = "";
            foreach($medias as $media_item){
                $mode = strtolower($media_item['nns_mode']);
                $media_arr[$mode] = $media_item;
            }
            if(!empty($media_arr['hd'])){
                $media = $media_arr['hd'];
            }else if(!empty($media_arr['std'])){
                $media = $media_arr['std'];
            }else if(!empty($media_arr['low'])){
                $media = $media_arr['low'];
            }
            if(empty($media)) return false;
                $video_profile =1;
                $mode = strtolower($media['nns_mode']);
                switch($mode){
                    case 'std':
                    $video_profile = 1;
                    break;
                    case 'hd':
                    $video_profile = 5;
                    break;
                    case 'low':
                    $video_profile = 3;
                    break;
                }                
                //判断片源的URL  
                if(empty($index_media['nns_date'])){
                    $index_media['nns_date'] = nl_db_get_col("select nns_date from nns_mgtvbk_clip_task where nns_id='{$index_media['nns_clip_task_id']}'", $db);
                }       
                $url = MOVIE_FTP.$index_media['nns_date'].'/'.$index_media['nns_clip_task_id'].'/'.$pinyin.'-'.$media['nns_vod_index'].'.m3u8';
                if(!empty($index_media['nns_file_path'])){
                    $url = MOVIE_FTP.$index_media['nns_file_path'];
                }
                $bool = self::check_ftp_file($url);
                if($bool===false){
                    DEBUG && i_write_log_core('path_fail----'.$url,$sp_id.'/path_fail');
                    nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='{$index_media['nns_task_id']}'", $db);
                    include_once 'queue_task_model.php';
                    $queue_task_model = new queue_task_model();
                    $queue_task_model->q_re_clip($index_media['nns_task_id']);
                    $queue_task_model=null;
                    return false;
                }
                
                $xml_str .= '<Object ElementType="Movie" ID="' .$index_media['nns_media_id']. '" Action="' . $action . '" Code="' .$index_media['nns_media_id']. '" >';
                $xml_str .= '<Property Name="Type">1</Property>';//媒体类型1:正片 2:预览片
                $xml_str .= '<Property Name="FileURL">' .$url. '</Property>';//媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
                $xml_str .= '<Property Name="SourceDRMType">1</Property>';//0: No DRM 1: BES DRM
                $xml_str .= '<Property Name="DestDRMType">1</Property>';//
                $xml_str .= '<Property Name="AudioType">1</Property>';//0: 其他 1: Monaural 单声道 2: Stereo 多声道 3: Two-nation monaural 双单声道 4: Two-nation stereo 双多声道  5: AC3(5:1 channel) AC3声道
                $xml_str .= '<Property Name="ClosedCaptioning">1</Property>';//0:无字幕 1:有字幕
                $xml_str .= '<Property Name="OCSURL"></Property>';//在海量存储中的视频URL，类似Rtsp://ip:port/1/2/3.ts      
                $xml_str .= '<Property Name="Duration"></Property>';//播放时长HHMISSFF （时分秒帧）
                $xml_str .= '<Property Name="FileSize">1024</Property>';//文件大小，单位为Byte
                $xml_str .= '<Property Name="BitRateType">1</Property>';//码流;1:1.6Mbps 2:2.1Mbps 3:8Mbps 4:60kbps 5:150kbps 6:420kbps 7:750kbps
                $xml_str .= '<Property Name="VideoType">1</Property>';//编码格式： 1:H.264 2:MPEG4 3:AVS 4:MPEG2 5:MP3 6:WMV
                $xml_str .= '<Property Name="AudioFormat">1</Property>';//编码格式：1.   MP2 2.  AAC 3.  AMR
                $xml_str .= '<Property Name="Resolution">1</Property>';//分辨率类型：1:QCIF 2:QVGA 3:2/3 D1 4:3/4 D1 5:D1 6:720P 7:1080i 8:1080P
                $xml_str .= '<Property Name="VideoProfile">'.$video_profile.'</Property>';//1:Simple 2:Advanced Simple 3:Baseline 4:Main 5:High 6:JiZhun
                $xml_str .= '<Property Name="SystemLayer">1</Property>';//1:TS 2:3GP
                $xml_str .= '<Property Name="ServiceType">0x01</Property>';//服务类型:0x01：在线播放(默认) 0x10：支持下载 0X11:  在线播放+下载                
                $xml_str .= '</Object>';
                $xml_str .= '</Objects>';
                $xml_str .= '<Mappings>';
                $xml_str .= '<Mapping ParentType="Program" ParentID="'.$index_media['nns_video_index_id'].'" ElementType="Movie" ElementID="'.$index_media['nns_media_id'].'" ParentCode="'.$index_media['nns_video_index_id'].'" ElementCode="'.$index_media['nns_media_id'].'" Action="'.$action.'">';
                $xml_str .= '</Mapping>';
                $xml_str .= '</Mappings>';
                $xml_str .= '</ADI>';
                $guid = np_guid_rand();
                $file_name = 'vod_media_'.$index_media['nns_media_id'].'_'.$action.'_'.$guid.'.xml';
                $c2_info = array(
                'nns_id' => $guid,
                'nns_task_type'=>'Movie',
                'nns_task_id'=> isset($index_media['nns_task_id'])?$index_media['nns_task_id']:null,
                'nns_task_name'=> isset($index_media['nns_task_name'])?$index_media['nns_task_name']:null,  
                'nns_action'=>  $action,                
                'nns_url' => $file_name,
                'nns_content' => $xml_str,
                //'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
                'nns_desc' => 'Movie,'.$action,
                );
            
            
            
            //修改切片的状态
            
            $clip_task_id = $index_media['nns_clip_task_id'];
            
            
            
            //更改状态
            $dt = date('Y-m-d H:i:s');
            $set_state = array(
            'nns_state' => clip_task_model::TASK_C_STATE_C2_HANDLE,
            'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
            'nns_modify_time'=>$dt,
            );
            clip_task_model::update_task($clip_task_id, $set_state);
                    
                    
            //任务日志  
            $task_log = array(
                'nns_task_id' => $clip_task_id,
                'nns_state'   => clip_task_model::TASK_C_STATE_C2_HANDLE,
                'nns_desc'    => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
            );  
            clip_task_model::add_task_log($task_log);
            return self::execute_c2($c2_info,$sp_id);

        }else{
            DEBUG && i_write_log_core('--没有片源--');
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$index_media['nns_task_id']}'", $db);
        }
        
    }
    
    /**
     * 
     * @name 检测这个片源是否在ftp服务器上
     */
    
    static  public function check_ftp_file($url){
        $url_arr = parse_url($url);
        $port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
        $time = 10;
        $connect_no=ftp_connect($url_arr['host'],$port,$time);
        if ($connect_no===FALSE) return FALSE;
        
        @ftp_login(
        $connect_no,
        $url_arr["user"],
        $url_arr["pass"]
        );
        //吉林联通要开启被动模式
        @ftp_pasv($connect_no,true);
        $contents = @ftp_nlist($connect_no, $url_arr['path']);
        if($contents===false){
            return FALSE;
        }else{
            if(empty($contents)){
                return FALSE;
            }
            return true;
        }
    }
    
    
    
    
    static public function __gateway_run($url,$log=NULL,$method='get',$params=NULL,$header=NULL){
        if ($method=='get'){
            $data = http_build_query($params);
            if (strpos('?',$url)>0){
                $url .='&'.$data;
            }else{
                $url .='?'.$data;
            }
        }       
        $ch = curl_init();      
        curl_setopt($ch, CURLOPT_HEADER, 0);        
        if (is_array($header)){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method=='post'){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //超时时间
        $output = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $reason = curl_error($ch);
        curl_close($ch);        
        $return=array(
            'data'=>$output,
            'code'=>$code,
            'reason'=>$reason
        ); 
        return $return;
    }
    

    static public function execute_c2($c2_info, $sp_id) {
        $c2_id = $c2_info['nns_id'];
        $sub_path = date('Y-m-d');
        $file = $c2_info['nns_url'];
        $c2_info['nns_url'] = $sub_path . '/' . $file;
        $xml_str = $c2_info['nns_content'];
        $file_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/mgtv/' . $sp_id . '/inject_xml/' . $sub_path . '/';

        if (!is_dir($file_path))
            mkdir($file_path, 0777, true);
        $file_path .= $file;
        file_put_contents($file_path, $xml_str);
        $CmdFileURL = C2_FTP . $c2_info['nns_url'];
        
        
        $post_data = array(
            'folder'=>$sub_path,
            'url'=>$file,
            'xml_data'=>$xml_str,
            'xml_ftp_addr'=>$CmdFileURL,
            'id'=>$c2_id,
        );
        
        $post_data = json_encode($post_data);
        $bool  = self::exists_c2_commond_child($c2_info, $sp_id);

        if ($bool===false) {            
            DEBUG && i_write_log_core('post_data----'.var_export(json_decode($post_data,true),true),$sp_id.'/post_data');
            $result = self::__gateway_run('http://221.181.100.156:58080/nn_gateway/shanghai_mobile/request_data.php', null, 'post', $post_data, null);
            if($result['code']==200){
                $re = json_decode($result['data'],true);
                $c2_info['nns_result'] = '[' .$re['Result']. ']';
                if($re['Result']!=0){
                    $c2_info['nns_result'] = '[-1]';
                    $c2_info['nns_notify_result'] = -1;
                }
            }else{
                $c2_info['nns_result'] = '[-1]';
                $c2_info['nns_notify_result'] = -1;
            }
            $c2_info['nns_id'] = $c2_id;
            self::save_c2_log_child($c2_info, $sp_id);
            return true;
        }
        return false;

    }

    static public function exists_c2_commond_child($c2_info, $sp_id) {
        $db_r = nn_get_db(NL_DB_READ);
        $nns_org_id = $sp_id;
        $nns_task_type = $c2_info['nns_task_type'];
        $nns_task_id = $c2_info['nns_task_id'];
        $nns_action = $c2_info['nns_action'];

        if (empty($nns_task_id))
            return false;
        $start_time = date('Y-m-d') . ' 00:00:00';
        $end_time = date('Y-m-d') . ' 23:59:59';
        $count = "select count(1) as num from nns_mgtvbk_c2_log where nns_org_id='{$sp_id}' and nns_task_id='{$nns_task_id}' and nns_task_type='{$nns_task_type}' and nns_action='{$nns_action}' and nns_create_time>='{$start_time}' and nns_create_time<='{$end_time}' and nns_notify_result is null";
        $c = nl_db_get_col($count, $db_r);
        
        if ($c >= 2) {
            return true;
        }else{
            return false;
        }
    }

    static public function save_c2_log_child($c2_log, $sp_id) {
        $db = nn_get_db(NL_DB_WRITE);
        //$db->open();
        $c2_log['nns_type'] = 'std';
        $c2_log['nns_org_id'] = $sp_id;
        $dt = date('Y-m-d H:i:s');
        $c2_log['nns_create_time'] = $dt;
        $c2_log['nns_send_time'] = $dt;
        return nl_db_insert($db, 'nns_mgtvbk_c2_log', $c2_log);
    }



    static public function save_c2_notify($c2_notify){
            DEBUG && i_write_log_core('---------save_c2_notify----------');
        $db = nn_get_db(NL_DB_WRITE);
        $dt = date('Y-m-d H:i:s');
        $wh_content ="";
        if($c2_notify['nns_notify_result']!='-1'){
            $wh_content = "nns_content='',";
        }
        $sql = "update nns_mgtvbk_c2_log set " .
                "nns_notify_result_url='".$c2_notify['nns_notify_result_url']."' ," .$wh_content.
                "nns_notify_result='".$c2_notify['nns_notify_result']."', nns_notify_time='".$dt."'," .
                "nns_modify_time='".$dt."' " .
                "where nns_id='".$c2_notify['nns_id']."'";
        nl_execute_by_db($sql,$db);
        $db_r = nn_get_db(NL_DB_READ);
        $sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
        $c2_info = nl_db_get_one($sql,$db_r);
        if($c2_info==false) return false;
        //如果回馈的消息是重发的消息
        if($c2_info['nns_again']>=1){
            return false;
        }
        if($c2_info['nns_task_type']=='Series' || $c2_info['nns_task_type']=='Program'||$c2_info['nns_task_type']=='Movie'){
            if($c2_notify['nns_notify_result']=='-1'){
                $sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目            
                /*if($c2_info['nns_action']=='REGIST'){
                    $sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_action='modify',nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目         
                }elseif($c2_info['nns_action']=='UPDATE'){
                    $sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_action='add',nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目
                }*/         
            }else{              
                $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
                
                //是否需要异步获取播放穿
                
                $sp_config = sp_model::get_sp_config($c2_info['nns_org_id']);
                $cdn_query_mediaurl_bool = false;
                if(isset($sp_config['cdn_query_mediaurl'])&&(int)$sp_config['cdn_query_mediaurl']===1){
                    $cdn_query_mediaurl_bool = true;
                }               
                if($cdn_query_mediaurl_bool&&$c2_info['nns_task_type']=='Movie'){                   
                    $sql_update = "update nns_mgtvbk_c2_task set nns_status=6,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
                    if($c2_info['nns_action']=='DELETE'){
                        $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
                    }
                }
            }
            nl_execute_by_db($sql_update,$db);  
        }
        
        if($c2_info['nns_task_type']=='Movie'){         
            $sql_c2_task = nl_db_get_one("select * from  nns_mgtvbk_c2_task  where nns_id='".$c2_info['nns_task_id']."'", $db);
            if($c2_info['nns_action']=='DELETE'){
                if($c2_notify['nns_notify_result']=='-1'){
                    $nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
                    $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];
                    //$sql = "update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='".$c2_info['nns_task_id']."'";
                    //nl_execute_by_db($sql,$db);       
                }else{
                    $nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
                    $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];
                    //$sql = "update nns_mgtvbk_c2_task set nns_status=0 where nns_id='".$c2_info['nns_task_id']."'";
                    //nl_execute_by_db($sql,$db);       
                    
                }
            }else{
                if($c2_notify['nns_notify_result']=='-1'){
                    $nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
                    $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];
                    //$sql = "update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='".$c2_info['nns_task_id']."'";
                    //nl_execute_by_db($sql,$db);       
                }else{
                    $nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
                    $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];
                    //$sql = "update nns_mgtvbk_c2_task set nns_status=0 where nns_id='".$c2_info['nns_task_id']."'";
                    //if($c2_info['nns_org_id']=='sihua'){
                    //  $sql = "update nns_mgtvbk_c2_task set nns_status=6 where nns_id='".$c2_info['nns_task_id']."'";
                    //}
                    //nl_execute_by_db($sql,$db);       
                    
                }
            }
                
            //更改切片状态
            $dt = date('Y-m-d H:i:s');
            $set_state = array(
            'nns_state' => $nns_state,
            'nns_desc' => $nns_desc,
            'nns_modify_time'=>$dt,
            );
            clip_task_model::update_task($sql_c2_task['nns_clip_task_id'], $set_state);
            //任务日志  
            $task_log = array(
            'nns_task_id' => $sql_c2_task['nns_clip_task_id'],
            'nns_state' => $nns_state,
            'nns_desc' => $nns_desc,
            );  
            clip_task_model::add_task_log($task_log);
        }



        if($c2_info['nns_task_type']=='QueryPlay'){
            if($c2_notify['nns_notify_result']=='-1'){
                $sql_update = "update nns_mgtvbk_c2_task set nns_status=9,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
            }else{
                $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97,nns_ex_url='".time()."' where nns_id='".$c2_info['nns_task_id']."'";
            }
            nl_execute_by_db($sql_update,$db);
        }

        //通知列队
        
        if($c2_notify['nns_notify_result']!='-1'){
            //$c2_info['nns_task_id']
            include_once dirname(dirname(dirname(__FILE__))).'/queue_task_model.php';
            $queue_task_model = new queue_task_model();
            //print_r($c2_info);
            $queue_task_model->q_report_task($c2_info['nns_task_id']);
            $q_model=null;
        }
        
        //下载结果
        if(!empty($c2_notify['nns_notify_result_url']))
            {
            
            $url_arr = parse_url($c2_notify['nns_notify_result_url']);
            $url_arr["path"] = str_replace("//","/",$url_arr["path"]);
            $port = isset($url_arr["port"])?$url_arr["port"]:21;
            include_once NPDIR . '/np_ftp.php'; //print_r($url_arr);
            $ftp1=new nns_ftp($url_arr['host'],$url_arr["user"],$url_arr["pass"],$port);
            $ftpcon1=$ftp1->connect();
            if (empty($ftpcon1)) {              
                return FALSE;
            }
            $notify_save_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$c2_info['nns_org_id'].'/notify'.$url_arr["path"];
            $path_parts = pathinfo($notify_save_path);
             if (!is_dir($path_parts['dirname'])){
                 mkdir($path_parts['dirname'], 0777, true);
             }            
            $rs = $ftp1->get(ltrim($url_arr["path"],'/'),$notify_save_path);
            if($rs==false){
                DEBUG && i_write_log_core('---------下载 notify 失败----------');
                return FALSE;
            }
        }
        
        
        
        
        return true;
    }


}